<template>
  <div>
    <Menu
      mode="horizontal"
      :active-name="activeName"
      @on-select="handleChangeMenu"
    >
      <MenuItem name="1">
        部位列表
      </MenuItem>
      <MenuItem name="2">
        半舱311列表
      </MenuItem>
      <!-- <MenuItem name="3">
                业务部位
            </MenuItem> -->
      <MenuItem name="4">
        白白管家
      </MenuItem>
    </Menu>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <div v-if="activeName === '1'">
        <Button type="primary" @click="handleAllocation()">新增</Button>
        <Table
          size="small"
          :loading="tableLoading"
          row-key="id"
          :columns="columns"
          :data="data"
          class="ivu-mt-16"
        >
          <template slot-scope="{ row }" slot="status">
            <Button
              v-if="row.status === '1'"
              type="success"
              size="small"
              @click="changeStatus(row)"
              >启用</Button
            >
            <Button
              v-if="row.status === '0'"
              type="error"
              size="small"
              @click="changeStatus(row)"
              >停用</Button
            >
          </template>
          <template slot-scope="{ row }" slot="operation">
            <a @click="handleAllocation(row)">编辑</a>
            <Divider type="vertical" />
            <a @click="delfuna(row)" style="color: red;">删除</a>
          </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
          <Page
            :total="total"
            :current.sync="page"
            show-total
            show-elevator
            :page-size="pageSize"
            @on-change="changePage"
            :page-size-opts="pageOpts"
            show-sizer
            transfer
            @on-page-size-change="changePageSize"
          />
        </div>
      </div>
      <div v-if="activeName === '2'">
        <Button type="primary" @click="handleOpenCreate">新增</Button>
        <Table
          size="small"
          :loading="tableLoadingTwo"
          :columns="columnBase"
          :data="dataList"
          class="ivu-mt-16"
        >
          <template slot-scope="{ row }" slot="status">
            <Button
              v-if="row.status === '1'"
              type="success"
              size="small"
              @click="handleChangeStatus(row)"
              >启用</Button
            >
            <Button
              v-if="row.status === '0'"
              type="error"
              size="small"
              @click="handleChangeStatus(row)"
              >停用</Button
            >
          </template>
          <template slot-scope="{ row, index }" slot="operation">
            <a @click="handleUpdata(index)">编辑</a>
            <Divider type="vertical" />
            <a @click="delfunb(row)" style="color: red;">删除</a>
          </template>
        </Table>
      </div>
      <div v-if="activeName === '3'">
        <Button type="primary" @click="handleAllocation()">新增</Button>
        <Table
          size="small"
          :loading="tableLoading"
          row-key="id"
          :columns="columns"
          :data="data"
          class="ivu-mt-16"
        >
          <template slot-scope="{ row }" slot="status">
            <Button
              v-if="row.status === '1'"
              type="success"
              size="small"
              @click="changeStatus(row)"
              >启用</Button
            >
            <Button
              v-if="row.status === '0'"
              type="error"
              size="small"
              @click="changeStatus(row)"
              >停用</Button
            >
          </template>
          <template slot-scope="{ row }" slot="operation">
            <a @click="handleAllocation(row)">编辑</a>
            <Divider type="vertical" />
            <a @click="delfunc(row)" style="color: red;">删除</a>
          </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
          <Page
            :total="total"
            :current.sync="page"
            show-total
            show-elevator
            :page-size="pageSize"
            @on-change="changePage"
            :page-size-opts="pageOpts"
            show-sizer
            transfer
            @on-page-size-change="changePageSize"
          />
        </div>
      </div>
      <div v-if="activeName === '4'">
        <Button type="primary" @click="handleAllocation2()">新增</Button>
        <Table
          size="small"
          :loading="tableLoading2"
          row-key="id"
          :columns="columns"
          :data="dataList2"
          class="ivu-mt-16"
        >
          <template slot-scope="{ row }" slot="status">
            <Button
              v-if="row.status === '1'"
              type="success"
              size="small"
              @click="changeStatus2(row)"
              >启用</Button
            >
            <Button
              v-if="row.status === '0'"
              type="error"
              size="small"
              @click="changeStatus2(row)"
              >停用</Button
            >
          </template>
          <template slot-scope="{ row }" slot="operation">
            <a @click="handleAllocation2(row)">编辑</a>
            <Divider type="vertical" />
            <a @click="delfund(row)" style="color: red;">删除</a>
          </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
          <Page
            :total="total"
            :current.sync="page"
            show-total
            show-elevator
            :page-size="pageSize"
            @on-change="changePage"
            :page-size-opts="pageOpts"
            show-sizer
            transfer
            @on-page-size-change="changePageSize"
          />
        </div>
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '编辑' : '新增'"
      :mask-closable="false"
      draggable
      @on-cancel="handleDrawerCancel()"
    >
      <Form
        :model="formItem"
        :rules="ruleValidate"
        ref="formItem"
        :label-width="80"
      >
        <FormItem label="名称" prop="input">
          <Input
            v-model="formItem.input"
            placeholder="请输入来源名称,批量新增用逗号分隔"
            clearable
          ></Input>
        </FormItem>
        <FormItem label="排序" prop="number">
          <Input
            v-model="formItem.number"
            type="number"
            placeholder="默认在现在排序后+1"
          ></Input>
        </FormItem>
        <FormItem label="父节点" prop="select" v-if="type === 0">
          <Select v-model="formItem.select" placeholder="默认根节点" clearable>
            <Option
              v-for="(item, index) in fatherList"
              :key="index"
              :value="item.id"
              >{{ item.body_parts_name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem v-if="edit" label="状态" prop="switch">
          <i-switch v-model="formItem.switch">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel()">取消</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="handleSubmit('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="showCreate"
      :title="title"
      draggable
      :loading="creating"
      @on-ok="handleSubmitCreate"
    >
      <Form
        :model="formData"
        ref="create"
        :rules="createRules"
        :label-width="80"
      >
        <FormItem label="名称" required prop="bc_parts_name">
          <Input
            v-model="formData.bc_parts_name"
            placeholder="请输入"
            clearable
          ></Input>
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="formData.status">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="modal2"
      :title="edit2 ? '编辑' : '新增'"
      :mask-closable="false"
      draggable
      @on-cancel="handleDrawerCancel2()"
    >
      <Form
        :model="formItem2"
        :rules="ruleValidate"
        ref="formItem2"
        :label-width="80"
      >
        <FormItem label="名称" prop="input">
          <Input
            v-model="formItem2.input"
            placeholder="请输入来源名称,批量新增用逗号分隔"
            clearable
          ></Input>
        </FormItem>
        <FormItem label="排序" prop="number">
          <Input
            v-model="formItem2.number"
            type="number"
            placeholder="默认在现在排序后+1"
          ></Input>
        </FormItem>
        <FormItem label="父节点" prop="select">
          <Select v-model="formItem2.select" placeholder="默认根节点" clearable>
            <Option
              v-for="(item, index) in fatherList2"
              :key="index"
              :value="item.id"
              >{{ item.body_parts_name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem v-if="edit2" label="状态" prop="switch">
          <i-switch v-model="formItem2.switch">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel2()">取消</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="handleSubmit2('formItem2')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  GetBodyPartList,
  GetBodyPartFatherList,
  CreateBodyPart,
  UpdateBodyPart,
  UpdateBodyPartStatus,
  BasePartsList,
  AddBaseParts,
  UpdataBaseParts,
  ChangeBaseParts,
  bbbodypartslist,
  bbbodypartscreate,
  bbbodypartsupdate,
  bbbodypartsinfo,
  bbbodypartsupdatestatus,
} from "@api/setting";
import {
  systembasebcbodypartstruedelete,
  systembasebbbodypartstruedelete,
  systembasebodypartstruedelete,
} from "@api/delete";

export default {
  data() {
    return {
      modal: false,
      modal2: false,
      edit: false,
      edit2: false,
      loading: false,
      tableLoading: false,
      tableLoadingTwo: false,
      tableLoading2: false,
      activeName: "1",
      formItem: {
        input: "",
        select: "",
        number: "",
        switch: true,
      },
      formItem2: {
        input: "",
        select: "",
        number: "",
        switch: true,
      },
      showCreate: false,
      creating: false,
      formData: {
        bc_parts_name: "",
        status: "",
      },
      title: "新增",
      updateIndex: -1,
      dataList: [],
      dataList2: [],
      createRules: {
        bc_parts_name: [
          { required: true, message: "部位名不可为空", trigger: "blur" },
        ],
      },
      ruleValidate: {
        input: [{ required: true, message: "部位名不可为空", trigger: "blur" }],
      },
      columnBase: [
        {
          title: "名称",
          key: "bc_parts_name",
        },
        {
          title: "状态",
          slot: "status",
        },
        {
          title: "操作",
          slot: "operation",
        },
      ],
      columns: [
        {
          title: "名称",
          key: "body_parts_name",
          tree: true,
        },
        {
          title: "排序",
          key: "sort",
        },
        {
          title: "状态",
          slot: "status",
        },
        {
          title: "操作",
          slot: "operation",
        },
      ],
      data: [],
      fatherList: [],
      fatherList2: [],
      pageOpts: [10, 20, 30, 50],
      page: 1,
      pageSize: 10,
      total: 0,
      type: 0,
    };
  },
  created() {
    this.onLoad();
  },
  methods: {
    delfuna(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          systembasebodypartstruedelete({ id: row.id }).then((res) => {
            this.$Message.info("删除成功");
            this.onLoad();
          });
        },
        onCancel: () => {},
      });
    },
    delfunb(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          systembasebcbodypartstruedelete({ id: row.id }).then((res) => {
            this.$Message.info("删除成功");
            this.onLoad();
          });
        },
        onCancel: () => {},
      });
    },
    delfunc(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          this.$Message.info("删除成功");
          this.onLoad();
        },
        onCancel: () => {},
      });
    },
    delfund(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          systembasebbbodypartstruedelete({ id: row.id }).then((res) => {
            this.$Message.info("删除成功");
            this.onLoad();
          });
        },
        onCancel: () => {},
      });
    },
    getFatherList() {
      /**
       * @description 部位一级列表
       */
      GetBodyPartFatherList().then((res) => {
        this.fatherList = res;
      });
    },
    onLoad() {
      /**
       * @description 部位列表
       * @param {Object} param page  {String} 页数
       * @param {Object} param pageSize {String} 条数/页
       */
      this.tableLoading = true;
      GetBodyPartList({
        type: this.type,
        page: this.page,
        pageSize: this.pageSize,
      })
        .then((res) => {
          this.data = res.list;
          this.page = res.page;
          this.pageSize = res.pageSize;
          this.total = res.total;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 切换menu菜单
    handleChangeMenu(e) {
      this.type = "";
      this.page = 1;
      this.pageSize = 10;
      this.activeName = e;
      if (this.activeName === "1") {
        this.type = 0;
        this.onLoad();
      } else if (this.activeName === "2") {
        this.getData();
      } else if (this.activeName === "3") {
        this.type = 1;
        this.onLoad();
      } else if (this.activeName === "4") {
        this.bblist();
      }
    },
    // 获取半仓311列表
    getData() {
      this.tableLoadingTwo = true;
      BasePartsList()
        .then((res) => {
          this.dataList = res.list;
        })
        .finally(() => {
          this.tableLoadingTwo = false;
        });
    },
    // 切换半仓311状态
    handleChangeStatus(row) {
      this.$Modal.confirm({
        title: "切换半舱311状态",
        content: "确定" + (row.status === "1" ? "停用" : "启用") + "当前状态?",
        onOk: () => {
          ChangeBaseParts({
            id: row.id,
            status: row.status === "1" ? "0" : "1",
          }).then(() => {
            this.$Message.success("修改成功");
            this.getData();
          });
        },
      });
    },
    // 半仓311编辑
    handleUpdata(index) {
      this.showCreate = true;
      this.$nextTick(() => {
        this.$refs["create"].resetFields();
        this.updateIndex = index;
        this.title = "编辑";
        const item = this.dataList[index];
        for (let key in this.formData) {
          if (key === "status") {
            this.formData[key] = item[key] === "1";
          } else {
            this.formData[key] = item[key];
          }
        }
        this.formData.id = item.id;
      });
    },
    // 半仓311新增
    handleOpenCreate() {
      this.updateIndex = -1;
      this.title = "新增";
      this.showCreate = true;
      this.$nextTick(() => {
        this.$refs["create"].resetFields();
      });
    },
    // 提交半仓311
    handleSubmitCreate() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.formData));
          sendData.status = sendData.status === true ? "1" : "0";
          if (this.updateIndex < 0) {
            AddBaseParts(sendData).then(() => {
              // 创建模块成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success("创建成功");
            });
          } else {
            UpdataBaseParts(sendData).then(() => {
              this.showCreate = false;
              this.getData();
              this.$Message.success("修改成功");
            });
          }
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        } else {
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        }
      });
    },
    // 部位列表切换分页
    changePage(page) {
      this.page = page;
      if (this.activeName === "1" || this.activeName === "3") {
        this.onLoad();
      } else {
        this.bblist();
      }
    },
    // 部位列表切换页数
    changePageSize(pagesize) {
      this.pageSize = pagesize;
      if (this.activeName === "1" || this.activeName === "3") {
        this.onLoad();
      } else {
        this.bblist();
      }
    },
    handleAllocation(row) {
      this.modal = true;
      this.getFatherList();
      if (row) {
        this.edit = true;
        this.formItem = {
          input: row.body_parts_name,
          select: row.pid,
          number: row.sort,
          switch: row.status === "1",
          id: row.id,
        };
      }
    },
    changeStatus(row) {
      const param = {
        id: row.id,
        status: row.status === "1" ? "0" : "1",
      };
      this.$Modal.confirm({
        title: "切换部位状态",
        content: "确定" + (row.status === "1" ? "停用" : "启用") + "当前部位?",
        onOk: () => {
          this.changeSubmit(param);
        },
      });
    },
    handleDrawerCancel() {
      this.modal = false;
      this.edit = false;
      this.$refs["formItem"].resetFields();
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            type: this.type,
            body_parts_name: this.formItem.input,
            pid: this.formItem.select,
            sort: this.formItem.number,
            status: this.formItem.switch ? "1" : "0",
          };
          if (this.edit) {
            params.id = this.formItem.id;
            this.updateSubmit(params);
          } else {
            this.createSubmit(params);
          }
        } else {
          console.log("表单校验失败！");
        }
      });
    },
    createSubmit(params) {
      CreateBodyPart(params)
        .then(() => {
          this.$Message.success(" 创建成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateSubmit(params) {
      UpdateBodyPart(params)
        .then(() => {
          this.$Message.success(" 修改成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    changeSubmit(params) {
      UpdateBodyPartStatus(params).then(() => {
        this.$Message.success("状态切换成功");
        this.onLoad();
      });
    },
    // 白白管家
    /**
     * @函数功能: bblist
     */
    bblist() {
      this.tableLoading2 = false;
      bbbodypartslist({
        page: this.page,
        pageSize: this.pageSize,
      })
        .then((res) => {
          this.dataList2 = res.list;
          this.page = res.page;
          this.pageSize = res.pageSize;
          this.total = res.total;
        })
        .finally(() => {
          this.tableLoading2 = false;
        });
    },
    /**
     * @函数功能: 白白管家新增或编辑
     * @参数1[row][对象]: 新增为空，编辑为列表单项数据
     */
    handleAllocation2(row) {
      this.modal2 = true;
      if (row) {
        this.getFatherList2(row.id);
        this.edit2 = true;
        this.formItem2 = {
          input: row.body_parts_name,
          select: row.pid,
          number: row.sort,
          switch: row.status === "1",
          id: row.id,
        };
      } else {
        this.getFatherList2(0);
      }
    },
    /**
     * @函数功能:
     */
    getFatherList2(id) {
      /**
       * @description 部位一级列表
       */
      bbbodypartsinfo({ id }).then((res) => {
        this.fatherList2 = res.body_list;
        console.log(this.fatherList2);
      });
    },
    /**
     * @函数功能: 白白管家新增或编辑取消
     */
    handleDrawerCancel2() {
      this.modal2 = false;
      this.edit2 = false;
      this.$refs["formItem2"].resetFields();
    },
    /**
     * @函数功能: 白白管家新增或编辑确定
     * @参数1[name][字符串]: 验证规则名
     */
    handleSubmit2(name) {
      this.$refs["formItem2"].validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = {
            id: "",
            body_parts_name: this.formItem2.input,
            pid: this.formItem2.select,
            sort: this.formItem2.number,
            status: this.formItem2.switch ? "1" : "0",
          };
          if (this.edit2) {
            params.id = this.formItem2.id;
            bbbodypartsupdate(params)
              .then(() => {
                this.$Message.success(" 修改成功");
                this.loading = false;
                this.bblist();
                this.handleDrawerCancel2();
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            bbbodypartscreate(params)
              .then(() => {
                this.$Message.success(" 修改成功");
                this.loading = false;
                this.bblist();
                this.handleDrawerCancel2();
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          console.log("表单校验失败！");
        }
      });
    },
    changeSubmit2(params) {
      bbbodypartsupdatestatus(params).then(() => {
        this.$Message.success("状态切换成功");
        this.bblist();
      });
    },

    changeStatus2(row) {
      const param = {
        id: row.id,
        status: row.status === "1" ? "0" : "1",
      };
      this.$Modal.confirm({
        title: "切换白白管家状态",
        content:
          "确定" + (row.status === "1" ? "停用" : "启用") + "当前白白管家?",
        onOk: () => {
          this.changeSubmit2(param);
        },
      });
    },
  },
};
</script>
<style scoped lang="less">
/deep/.ivu-menu {
  z-index: 1;
}
</style>
